package com.qsmx.qingqiuticket.app.delegate.group;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateGroupOrderBinding;
import com.qsmx.qingqiuticket.app.delegate.HomeDelegate;
import com.qsmx.qingqiuticket.app.delegate.HomeLoginMemDelegate;
import com.qsmx.qingqiuticket.app.delegate.OrderPayDelegate;
import com.qsmx.qingqiuticket.app.delegate.mem.MemTicketListDelegate;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.GroupVerifiedEntity;
import com.qsmx.qingqiuticket.app.entity.LockSessionEntity;
import com.qsmx.qingqiuticket.app.entity.PrintEntity;
import com.qsmx.qingqiuticket.app.entity.PrintInfoEntity;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.event.LoginEvent;
import com.qsmx.qingqiuticket.app.event.PrintFinishEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.LogUtils;
import com.qsmx.qingqiuticket.app.util.PrintUtil;
import com.qsmx.qingqiuticket.app.util.SaveHelper;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class GroupOrderDelegate extends AtmosDelegate {

    private List<GroupVerifiedEntity.BodyBean> mPrintData;
    private int mAllPrintTicketNum;

    private String orderNo = "";
    private String doorTicket = "";
    private String onceTicket = "";
    private String sessionTime = "";
    private String sessionNo = "";
    private String giveIntegral = "";
    private String giveGrowth = "";
    private String code = "";
    private String verifyNum = "";
    private DelegateGroupOrderBinding mBinding;
    private CountDownTimerUtil timer;
    /**
     * 打印中弹窗
     */
    private Dialog mPrintTicketDialog;
    private AppCompatTextView tvTicketOutNum;
    private AppCompatTextView tvPrintGetTicket;
    private AppCompatTextView tvPrintFinishTime;
    private AppCompatTextView tvPrintStatus;
    private AppCompatTextView tvBackNow;
    private AppCompatTextView tvPrintErrorInfo;
    private AppCompatTextView tvRetry;

    private Dialog mustLoginDialog;
    private Dialog unMustLoginDialog;
    private CountDownTimerUtil backTimer;
    private Dialog printErrorDialog;

    private int perGiveIntegral = 0;
    private int perGiveGrowth = 0;

    private AppCompatTextView tvErrorBackNow;
    private CountDownTimerUtil errorBackTime;

    @Override
    public Object setLayout() {
        return R.layout.delegate_group_order;
    }

    public static GroupOrderDelegate create(String orderNo, String doorTicket, String onceTicket, String sessionTime, String sessionNo, String giveIntegral, String giveGrowth, String code, String verifyNum, int perGiveIntegral, int perGiveGrowth) {
        final Bundle args = new Bundle();
        args.putString(FusionTag.ORDER_NO, orderNo);
        args.putString(FusionTag.DOOR_TICKET, doorTicket);
        args.putString(FusionTag.ONCE_TICKET, onceTicket);
        args.putString(FusionTag.SESSION_TIME, sessionTime);
        args.putString(FusionTag.SESSION_NO, sessionNo);
        args.putString(FusionTag.GIVE_INTEGRAL, giveIntegral);
        args.putString(FusionTag.GIVE_GROWTH, giveGrowth);
        args.putString(FusionTag.CODE, code);
        args.putString(FusionTag.VERIFY_NUM, verifyNum);
        args.putInt(FusionTag.PER_GIVE_INTEGRAL, perGiveIntegral);
        args.putInt(FusionTag.PER_GIVE_GROWTH, perGiveGrowth);

        final GroupOrderDelegate delegate = new GroupOrderDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            orderNo = args.getString(FusionTag.ORDER_NO);
            doorTicket = args.getString(FusionTag.DOOR_TICKET);
            onceTicket = args.getString(FusionTag.ONCE_TICKET);
            sessionTime = args.getString(FusionTag.SESSION_TIME);
            sessionNo = args.getString(FusionTag.SESSION_NO);
            giveIntegral = args.getString(FusionTag.GIVE_INTEGRAL);
            giveGrowth = args.getString(FusionTag.GIVE_GROWTH);
            code = args.getString(FusionTag.CODE);
            verifyNum = args.getString(FusionTag.VERIFY_NUM);
            perGiveIntegral = args.getInt(FusionTag.PER_GIVE_INTEGRAL, 0);
            perGiveGrowth = args.getInt(FusionTag.PER_GIVE_GROWTH, 0);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBinding = DelegateGroupOrderBinding.bind(rootView);
        startCountDownBackTime(120);

        if (AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE).equals("1") || StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE))) {
            if (FusionData.mMemData == null) {
                showLoginMemDialog();
            }
        } else {
            if (FusionData.mMemData == null) {
                showUnMustLoginMemDialog();
            }
        }

        mBinding.tvOrderNo.setText(orderNo);
        mBinding.tvDoorTicket.setText(doorTicket + "张");
        mBinding.tvOnceTicket.setText(onceTicket + "张");
        mBinding.tvIntoTime.setText(sessionTime);
        mBinding.tvSessionNo.setText("场次" + sessionNo);
        if (FusionData.mMemData != null) {
            mBinding.tvMemStatus.setText(FusionData.mMemData.getPhone());
            mBinding.tvMemStatus.setVisibility(View.VISIBLE);
            mBinding.tvPoint.setText(perGiveIntegral * StringUtil.IntegerValueOf(verifyNum, 0) + "");
            mBinding.tvUpPoint.setText(perGiveGrowth * StringUtil.IntegerValueOf(verifyNum, 0) + "");
        } else {
            mBinding.tvMemStatus.setText("未登录");
            mBinding.tvPoint.setText("0");
            mBinding.tvUpPoint.setText("0");
        }
        mBinding.ivBack.setOnClickListener(v -> {
            if (ClickUtil.isNotFastClick()) {
                if (getSupportDelegate() != null) {
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.tvMemStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (FusionData.mMemData == null) {
                        getSupportDelegate().start(new HomeLoginMemDelegate());
                    }
                }
            }
        });

        mBinding.ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (FusionData.mMemData == null) {
                        getSupportDelegate().start(new HomeLoginMemDelegate());
                    }
                }
            }
        });

        mBinding.tvTicketOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                groupVerify();
            }
        });
    }

    private void showLoginMemDialog() {
        mustLoginDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        mustLoginDialog.setCancelable(false);
        mustLoginDialog.show();
        Window window = mustLoginDialog.getWindow();
        window.setContentView(R.layout.dialog_login_mem_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvLogin = window.findViewById(R.id.tv_login);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mustLoginDialog.dismiss();
                getSupportDelegate().start(new HomeLoginMemDelegate());
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mustLoginDialog.dismiss();
                getSupportDelegate().pop();
            }
        });
    }

    private void showUnMustLoginMemDialog() {
        unMustLoginDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        unMustLoginDialog.setCancelable(true);
        unMustLoginDialog.show();
        Window window = unMustLoginDialog.getWindow();
        window.setContentView(R.layout.dialog_un_must_login_mem_tips);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvLogin = window.findViewById(R.id.tv_login);
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unMustLoginDialog.dismiss();
                getSupportDelegate().start(new HomeLoginMemDelegate());
            }
        });

        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unMustLoginDialog.dismiss();
            }
        });
    }

    private void groupVerify() {
        CameraManager.takeVideo(getContext(), orderNo, getProxyActivity());

        if (backTimer != null) {
            backTimer.cancel();
        }
        mPrintData = new ArrayList<>();
        DialogUtil.showLoadingDialog(getContext(), "正在出票...");
        JSONObject params = new JSONObject();
        params.put("verifiedCode", code);
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("verifiedNum", verifyNum);
        params.put("orderNo", orderNo);
        params.put("memberUuid", FusionData.mMemData != null ? FusionData.mMemData.getUserId() : "");

        LogUtils.saveLog2File(params.toString(), true);

        HttpHelper.RestClientPostRaw(params, HttpUrl.GROUP_VERIFIED,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        LogUtils.saveLog2File(response, false);
                        DialogUtil.dismissLoadingDialog();
                        Type type = new TypeToken<GroupVerifiedEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        GroupVerifiedEntity mData = gson.fromJson(response, type);

                        if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                            for (GroupVerifiedEntity.BodyBean data : mData.getBody()) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_BRAND_NAME, data.getPrintBrandName());
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_STORE_NAME, data.getPrintStoreName());
                                if (StringUtil.isNotEmpty(data.getPrintId())) {
                                    mPrintData.add(data);
                                }
                            }
                            mAllPrintTicketNum = mPrintData.size();
                            if (!mPrintData.isEmpty()) {
                                showPrintTicketDialog();
                                startPrintTicket();
                            } else {
                                DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), "门票未配置打印物料,请联系工作人员！", "确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtil.dismissErrorDialog();
                                        getSupportDelegate().popTo(HomeDelegate.class, false);
                                        FusionData.mMemData = null;
                                        EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
                                    }
                                });
                            }
                        } else if (mData.getHeader().getCode().equals("100009994")) {
                            DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), mData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    startCountDownBackTime(120);
                                    DialogUtil.dismissErrorDialog();
                                }
                            });
                        } else if (mData.getHeader().getCode().equals("100009995")) {
                            DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), mData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    startCountDownBackTime(120);
                                    DialogUtil.dismissErrorDialog();
                                }
                            });
                        } else if (mData.getHeader().getCode().equals("100009999")) {
                            DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), mData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DialogUtil.dismissErrorDialog();
                                    getSupportDelegate().popTo(HomeDelegate.class, false);
                                }
                            });
                        } else if (mData.getHeader().getCode().equals("10")) {
                            showPrintErrorDialog(mData.getHeader().getMessage());
                        } else {
                            DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), mData.getHeader().getMessage(), "确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    getSupportDelegate().pop();
                                }
                            });
                        }

//                        startPrintTicket();
//                        showPrintTicketDialog();
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), msg, "确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startCountDownBackTime(120);
                                DialogUtil.dismissErrorDialog();
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, getContext(), getString(R.string.un_know_net_error), "确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startCountDownBackTime(120);
                                DialogUtil.dismissErrorDialog();
                            }
                        });
                    }
                });

    }

    private void showPrintErrorDialog(String errorInfo) {
        printErrorDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        printErrorDialog.setCancelable(false);
        printErrorDialog.show();
        Window window = printErrorDialog.getWindow();
        window.setContentView(R.layout.dialog_print_error);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvErrorInfo = window.findViewById(R.id.tv_print_error_info);

        tvErrorInfo.setText(errorInfo);

        startErrorCountDownTime(10);

        tvErrorBackNow = window.findViewById(R.id.tv_back_now);

        tvErrorBackNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                printErrorDialog.dismiss();
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        });

        tvErrorBackNow.setClickable(false);
        tvErrorBackNow.setBackgroundResource(R.drawable.round_corner_dark_gray_bg_gray_line);
    }


    private void startPrintTicket() {
        if (mPrintData != null && !mPrintData.isEmpty()) {
            PrintInfoEntity data = new PrintInfoEntity();
            data.setId(mPrintData.get(0).getTicketId());
            data.setOrderNo(mPrintData.get(0).getOrderNo());
            data.setType(mPrintData.get(0).getTradeType());
            data.setQrCode(mPrintData.get(0).getBindUuid());
            data.setSessionNo(mPrintData.get(0).getSessionNo());
            data.setSessionDate(mPrintData.get(0).getSessionDate());
            data.setSessionTime(mPrintData.get(0).getSessionStartTime() + "-" + mPrintData.get(0).getSessionEndTime());
            data.setPrintWord(mPrintData.get(0).getPrintedWord());
            data.setTicketPrintName(mPrintData.get(0).getTicketPrintName());

            PrintUtil.doPrint(requireContext(), mPrintData.get(0).getPrintId(), tvPrintErrorInfo, tvRetry, data,getProxyActivity());
        } else {
            new android.os.Handler().postDelayed(CameraManager::stopRecording, 10000); // 10 秒后停止录制
            FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            tvBackNow.setVisibility(View.VISIBLE);
            tvPrintStatus.setText("打印完成");
            tvPrintGetTicket.setVisibility(View.VISIBLE);
            tvPrintFinishTime.setVisibility(View.VISIBLE);
            startCountDownTime(5);
        }
        tvTicketOutNum.setText(Html.fromHtml(String.format(getString(R.string.print_ticket_num), String.valueOf(mAllPrintTicketNum - mPrintData.size()), String.valueOf(mAllPrintTicketNum))));
    }

    @SuppressLint("SetTextI18n")
    public void showPrintTicketDialog() {
        if (mPrintTicketDialog != null) {
            mPrintTicketDialog.dismiss();
        } else {
            mPrintTicketDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }
        SoundPlayUtils.play(4);

        mPrintTicketDialog.setCancelable(false);
        Window window = mPrintTicketDialog.getWindow();
        window.setContentView(R.layout.dialog_ticket_out);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        tvPrintStatus = window.findViewById(R.id.tv_print_status);
        tvTicketOutNum = window.findViewById(R.id.tv_ticket_out_num);
        tvPrintGetTicket = window.findViewById(R.id.tv_print_get_ticket);
        tvPrintFinishTime = window.findViewById(R.id.tv_print_finish_time);
        tvBackNow = window.findViewById(R.id.tv_back_now);
        tvPrintErrorInfo = window.findViewById(R.id.tv_print_error_info);
        tvRetry = window.findViewById(R.id.tv_retry);
        AppCompatTextView tvOrderNo = window.findViewById(R.id.tv_order_no);

        tvOrderNo.setText("订单号：" + orderNo);

        tvRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPrintTicket();
                tvRetry.setVisibility(View.GONE);
                tvPrintErrorInfo.setVisibility(View.GONE);
            }
        });

        tvBackNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPrintTicketDialog.dismiss();
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));
                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        });
        mPrintTicketDialog.show();
    }

    private void startErrorCountDownTime(final long time) {
        if (errorBackTime != null) {
            errorBackTime.cancel();
        }
        errorBackTime = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvErrorBackNow.setText(String.format(getString(R.string.close_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                tvErrorBackNow.setText("关闭");
                tvErrorBackNow.setBackgroundResource(R.drawable.round_corner_back_btn_bg);
                tvErrorBackNow.setClickable(true);
            }
        };
        errorBackTime.start();// 开始计时
    }

    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvPrintFinishTime.setText(String.format(getString(R.string.finish_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                if (mPrintTicketDialog != null) {
                    mPrintTicketDialog.dismiss();
                }
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));

                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        };
        timer.start();// 开始计时
    }

    private void startCountDownBackTime(final long time) {
        if (backTimer != null) {
            backTimer.cancel();
        }
        backTimer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvTime.setText(String.format(getString(R.string.back_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                if (mPrintTicketDialog != null) {
                    mPrintTicketDialog.dismiss();
                }
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        backTimer.start();// 开始计时
    }

    private void printFinish(String printId, String orderNo, String ticketId) {
        DialogUtil.showLoadingDialog(requireContext(), "正在记录门票信息...");
        long orderNoTime = System.currentTimeMillis();
        String serialNo = "LS" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

        JSONObject params = new JSONObject();
        params.put("serialNo", serialNo);
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("printId", printId);
        params.put("orderNo", orderNo);
        params.put("ticketId", ticketId);
        params.put("changeNum", "1");
        params.put("changeType", "1");
        if (printId.equals("1")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
        } else if (printId.equals("2")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
        } else if (printId.equals("3")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));
        }

        HttpHelper.RestClientPostRaw(params, HttpUrl.PRINT_RECORD,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        Type type = new TypeToken<BaseEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        BaseEntity mData = gson.fromJson(response, type);
                        if (mData.getHeader().getCode().equals("200")) {
                            if (printId.equals("1")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("2")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("3")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM), 0) - 1));
                            }
                            mPrintData.remove(0);
                            startPrintTicket();
                        } else {
                            DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, requireContext(), mData.getHeader().getMessage(), "重试", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    printFinish(printId, orderNo, ticketId);
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, requireContext(), msg, "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(GroupOrderDelegate.this, requireContext(), getString(R.string.un_know_net_error), "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                });
    }

    private void cleanSessionInfo() {

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));

        HttpHelper.RestClientPostRaw(params, HttpUrl.CLEAR_SESSION,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPrintFinishEvent(PrintFinishEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                printFinish(mPrintData.get(0).getPrintId(), orderNo, mPrintData.get(0).getTicketId());
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        if (event != null && event.getData() != null) {
            if (FusionData.mMemData != null) {
                mBinding.tvMemStatus.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
                mBinding.tvMemStatus.setVisibility(View.VISIBLE);
                mBinding.tvPoint.setText(perGiveIntegral * StringUtil.IntegerValueOf(verifyNum, 0) + "");
                mBinding.tvUpPoint.setText(perGiveGrowth * StringUtil.IntegerValueOf(verifyNum, 0) + "");
            } else {
                mBinding.tvMemStatus.setText("未登录");
                mBinding.tvPoint.setText("0");
                mBinding.tvUpPoint.setText("0");
                if (AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE).equals("1") || StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.LOGIN_TYPE))) {
                    showLoginMemDialog();
                }
            }
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownBackTime(120);
        FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
        FusionCode.QrIsLoading = false;
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        if (backTimer != null) {
            backTimer.cancel();
        }
        if (mustLoginDialog != null) {
            mustLoginDialog.dismiss();
        }
        if (unMustLoginDialog != null) {
            unMustLoginDialog.dismiss();
        }
        DialogUtil.dismissErrorDialog();
        cleanSessionInfo();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
